package com.abc.pro.api;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

public class HttpGetTask extends AsyncTask<HttpUriRequest, Integer, JSONObject>{
    private static final String TAG = "HttpTask";
    @Override
    protected JSONObject doInBackground(HttpUriRequest...params) {
        // Performed on Background Thread
        HttpUriRequest request = params[0];
        HttpClient client = new DefaultHttpClient();
        
        try {
            // The UI Thread shouldn't be blocked long enough to do the reading in of the stream.
            HttpResponse response =  client.execute(request);
            
            // TODO handle bad response codes (such as 404, etc)
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            StringBuilder builder = new StringBuilder();
            for (String line = null; (line = reader.readLine()) != null; ) {
                builder.append(line).append("\n");
            }
            if(TextUtils.isEmpty(builder.toString())) return null;
            JSONTokener tokener = new JSONTokener(builder.toString());
            JSONObject json = new JSONObject(tokener);
            return json;
        } catch (Exception e) {
            // TODO handle different exception cases
            Log.e(TAG,e.toString());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        // Done on notify to UI Thread
        if(json != null) {
            mTaskHandler.taskSuccessful(json);
        } else {
            mTaskHandler.taskFailed();
        }
    }
    
    private HttpTaskHandler mTaskHandler;
    public void setTaskHandler(HttpTaskHandler taskHandler) {
        this.mTaskHandler = taskHandler;
    }
    
    public static interface HttpTaskHandler {
        void taskSuccessful(JSONObject json);
        void taskFailed();
    }

 
}
